package com.sfac.javaSpringBoot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/*
* 删除 /log下非当日日志文件
* */
@WebListener
public class LogDestroyListener implements ServletContextListener {
    private final static Logger LOGGER =  LoggerFactory.getLogger(LogDestroyListener.class);
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("====Init Contex====");
        File destFolder = new File("/log");
        if (destFolder == null || !destFolder.exists()){
            return;
        }

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = dtf.format(LocalDateTime.now());
        File[] files = destFolder.listFiles();
        for (File file : files){
            String fileName = file.getName();
            if (!fileName.contains(currentDate)){
                file.delete();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("====Destroy Contex====");
    }
}
